package com.xinxing.learning.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

import java.util.HashMap;

@Slf4j
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin", "supper").build());
        inMemoryUserDetailsManager.createUser(User.withUsername("wangwu").password("{noop}123").roles("user", "supper").build());
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/demo").hasRole("admin")
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "请先登录");
                    result.put("status", HttpStatus.UNAUTHORIZED.value());
                    response.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("configure() returned: " + resultStr);
                    response.getWriter().println(resultStr);
                })
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "无访问权限");
                    result.put("status", HttpStatus.FORBIDDEN.value());
                    response.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("configure() returned: " + resultStr);
                    response.getWriter().println(resultStr);
                })
                .and().formLogin()
                .and().csrf().disable()
        ;
    }
}
